<script setup lang="ts" name="Gen">
import importTable from './importTable.vue'
import { delTableApi, genCodeApi, listTableApi, synchDbApi } from "@/api/tool/gen";

const { proxy } = getCurrentInstance();

const router = useRouter();

const route = useRoute();

// 代码生成表格列表
const tableList = ref<GenTableRecord[]>([]);

// 加载
const loading = ref(false);

// 选中数组
const selection = ref<GenTableRecord[]>([])

// 非单个禁用
const single = ref(true);

// 非多个禁用
const multiple = ref(true);

// 弹窗标题
const title = ref('');

// 总条数
const total = ref(0);

// 创建时间选择
const dateRange = ref<[string, string]>(['', '']);

// 导入弹窗
const openImport = ref(false);

// 搜索栏元素
const queryGenRef = ref();

// 搜索栏
const queryParams = ref<GenTableRecord>({
  pageNum: 1,
  pageSize: 10,
  tableName: null,
  tableComment: null
})

/** 查询表集合 */
function getList() {
  loading.value = true;
  listTableApi(addDateRange(queryParams.value, dateRange.value)).then(response => {
    tableList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  if (refresh) {
    getList();
  }
  openImport.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = ['', ''];
  queryGenRef.value.resetFields()
  handleQuery();
}

/** 生成代码操作 */
function handleGenTable(row: GenTableRecord) {
  const tbNames = row.tableName || selection.value.map(item => item.tableName);
  if (tbNames == "") {
    proxy.$modal.msgError("请选择要生成的数据");
    return;
  }
  if (row.genType === "1") {
    genCodeApi(row.tableName).then(() => {
      proxy.$modal.msgSuccess("成功生成到自定义路径：" + row.genPath);
    });
  } else {
    download("/tool/gen/batchGenCode", { tables: tbNames }, "bige.zip", 'get');
  }
}

/** 同步数据库操作 */
function handleSynchDb(row: GenTableRecord) {
  const tableName = row.tableName;
  proxy.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(function () {
    return synchDbApi(tableName);
  }).then(() => {
    proxy.$modal.msgSuccess("同步成功");
  }).catch(() => {
  });
}

/** 打开导入表弹窗 */
function handleImport() {
  openImport.value = true;
  title.value = '导入表'
}

/** 预览按钮 */
function handlePreview(row: GenTableRecord) {
  router.push('/tool/gen/codeview/' + row.tableId);
}

/** 多选框选中数据 */
function handleSelectionChange(selectionList: GenTableRecord[]) {
  selection.value = selectionList;
  single.value = selectionList.length != 1;
  multiple.value = !selectionList.length;
}

/** 修改按钮操作 */
function handleEditTable(row: GenTableRecord) {
  const tableId = row.tableId;
  router.push({ path: "/tool/gen/edit/" + tableId, query: { pageNum: queryParams.value.pageNum } });
}

/** 删除按钮操作 */
function handleDelete(row: GenTableRecord) {
  let classNames = [];
  let tableIds = [];
  if (row.tableId) {
    classNames = [row.className];
    tableIds = [row.tableId];
  } else {
    selection.value.forEach(item => {
      classNames.push(item.className);
      tableIds.push(item.tableId);
    })
  }
  // @ts-ignore
  proxy.$modal.confirm('是否确认删除表名称为"' + classNames + '"的数据项？').then(() => {
    return delTableApi(tableIds);
  }).then(() => {
    getList();
    // @ts-ignore
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

onActivated(() => {
  getList();
})
getList();
</script>

<template>
  <div class="app-container">
    <div class="back-item">
      <el-form :model="queryParams" ref="queryGenRef" :inline="true">
        <el-form-item label="表名称" prop="tableName">
          <el-input
              v-model="queryParams.tableName"
              placeholder="请输入表名称"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="表描述" prop="tableComment">
          <el-input
              v-model="queryParams.tableComment"
              placeholder="请输入表描述"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item class="item-search">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="back-item">
      <div class="table-top mb8">
        <div class="title title-left">
          代码生成
        </div>
        <el-button
            type="primary"
            plain
            icon="Download"
            :disabled="multiple"
            @click="handleGenTable"
            v-hasPermi="['tool:gen:code']"
        >生成
        </el-button>
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['tool:gen:import']"
        >导入
        </el-button>
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['tool:gen:remove']"
        >删除
        </el-button>
        <span class="table-top-line" />
        <right-toolbar @queryTable="getList" />
      </div>
      <el-table
          v-loading="loading"
          :data="tableList"
          stripe
          v-tablesticky
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="表名称" align="center" prop="tableName" min-width="120" show-overflow-tooltip />
        <el-table-column label="表描述" align="center" prop="tableComment" min-width="120" show-overflow-tooltip />
        <el-table-column label="实体" align="center" prop="className" min-width="120" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-tooltip content="预览" placement="top">
              <el-button link type="primary" icon="View" @click="handlePreview(scope.row)"
                         v-hasPermi="['tool:gen:preview']"></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleEditTable(scope.row)"
                         v-hasPermi="['tool:gen:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['tool:gen:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="同步" placement="top">
              <el-button link type="primary" icon="Refresh" @click="handleSynchDb(scope.row)"
                         v-hasPermi="['tool:gen:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="生成代码" placement="top">
              <el-button link type="primary" icon="Download" @click="handleGenTable(scope.row)"
                         v-hasPermi="['tool:gen:code']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          :total="total"
          open-fixed
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
      <div class="line-magin" />
    </div>
    <import-table v-if="openImport" :title="title" @closeDialog="closeDialog" />
  </div>
</template>

<style scoped lang="scss">

</style>